package com.seari.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import sun.jvmstat.monitor.MonitorException;
import sun.jvmstat.monitor.MonitoredHost;
import sun.jvmstat.monitor.MonitoredVm;
import sun.jvmstat.monitor.MonitoredVmUtil;
import sun.jvmstat.monitor.VmIdentifier;

public class ProcessUtil
{
	
	
	public static Map<String, String> getProcessList() throws MonitorException, URISyntaxException
	{
		Map<String, String> pidMap = new HashMap<>();
		MonitoredHost local = MonitoredHost.getMonitoredHost("localhost");
	     // 取得所有在活动的虚拟机集合
	     Set<?> vmlist = new HashSet<Object>(local.activeVms());
	     // 遍历集合，输出PID和进程名
	     for(Object process : vmlist) {
	       MonitoredVm vm = local.getMonitoredVm(new VmIdentifier("//" + process));
	       // 获取类名
	       String processname = MonitoredVmUtil.mainClass(vm, true);
	       if(StringUtils.isNotBlank(processname))
	       {
	    	   pidMap.put(process.toString(), processname);
	       }
	     }
		return pidMap;
	}
	
	public static String getProcessIdByName(String processName) throws MonitorException, URISyntaxException
	{
		String result = "";
		Map<String, String> pidMap = getProcessList();
		for (Entry<String, String> entry : pidMap.entrySet())
		{
			if(entry.getValue().contains(processName))
			{
				result = entry.getKey();
				break;
			}
		}
		return result;
	}
	
	public static int executeCommand(String command)
	{
		int result = -1;
		Runtime rt = Runtime.getRuntime(); //Runtime.getRuntime()返回当前应用程序的Runtime对象
        Process ps = null;  //Process可以控制该子进程的执行或获取该子进程的信息。
        try {
            ps = rt.exec(command);   //该对象的exec()方法指示Java虚拟机创建一个子进程执行指定的可执行程序，并返回与该子进程对应的Process对象实例。
            ps.waitFor();  //等待子进程完成再往下执行。
            result = ps.exitValue();  //接收执行完毕的返回值
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
        	ps.destroy();  //销毁子进程
            ps = null;  
		} 
		return result;
	}
}
